package org.mspring.platform.security.service;

import org.apache.commons.codec.digest.DigestUtils;
import org.mspring.platform.dao.Page;
import org.mspring.platform.dao.query.QueryBuilder;
import org.mspring.platform.security.dao.UserDao;
import org.mspring.platform.security.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Gao Youbo
 * @since 2012-7-12
 */
@Service
@Transactional
public class UserService {

    @Autowired
    private UserDao userDao;

    /**
     * 验证用户，如果用户存在返回用户如果不存在返回NULL
     *
     * @param username
     * @param password
     * @return
     */
    public User validateUser(String username, String password) {
        password = DigestUtils.md5Hex(password);
        return userDao.findUser(username, password);
    }

    /**
     * 根据名字获取用户
     *
     * @param username
     * @return
     */
    public User findByUsername(String username) {
        return userDao.findByUsername(username);
    }

    /**
     * 根据Email获取用户
     *
     * @param email
     * @return
     */
    public User findByEmail(String email) {
        return userDao.findByEmail(email);
    }

    /**
     * 根据别名获取用户
     *
     * @param alias
     * @return
     */
    public User findByAlias(String alias) {
        return userDao.findByAlias(alias);
    }

    public User get(long id) {
        return userDao.get(id);
    }

    public Page<User> listPage(QueryBuilder queryBuilder, Page<User> page) {
        return userDao.listPage(queryBuilder, page);
    }

    public void update(User user) {
        userDao.update(user);
    }

    /**
     * 添加用户
     *
     * @param user
     * @return
     */

    public Long insert(User user) {
        return userDao.insert(user);
    }

    /**
     * 删除用户
     *
     * @param id
     */

    public void delete(long id) {
        User user = get(id);
        user.setDeleted(true);
        userDao.update(user);
    }

}
